package chances.system.data;

import java.io.File;
import java.io.OutputStream;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class ExcelWriter {
	private File templateFile;
	private OutputStream writeFile;
	private int row = 1;
	WritableSheet sheet;
	WritableWorkbook writeBook;

	public ExcelWriter(File src, OutputStream target) throws Exception {
		this.templateFile = src;
		this.writeFile = target;
		init();
	}

	public void init() throws Exception {
		writeBook = Workbook.createWorkbook(this.writeFile);
	}
	
	public void createSheet(String title, int index) throws Exception {
		Workbook book = Workbook.getWorkbook(this.templateFile);
		Sheet readSheet = book.getSheet(0);
		sheet = writeBook.createSheet(title, index);
		row = 1;

		for (int i = 0; i < readSheet.getColumns(); i++) {
			Cell acell = readSheet.getCell(i, 0);
			Label label = new Label(i, 0, acell.getContents());
			sheet.addCell(label);
		}
	}

	public ExcelWriter append(String line) throws Exception {
		String[] lines = line.split(",");
		return append(lines);
	}

	public ExcelWriter append(String[] columns) throws Exception {

		for (int i = 0; i < columns.length; i++) {
			Label label = new Label(i, row, columns[i]);
			sheet.addCell(label);
		}
		row++;
		return this;
	}

	public void save() throws Exception {
		writeBook.write();
		writeBook.close();
	}

	public void close() throws Exception {
		writeBook.close();
	}
}
